<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="http://at.alicdn.com/t/font_1309180_m0vigzfu7y.css">
    <script src="./js/jquery-3.6.1.js"></script>
    <script src="./js/animate.js"></script>
    <script src="./js/lunBoTu.js"></script>
    <title>华农荟园王电影点评</title>
    <link rel="stylesheet" href="css/dashboard.css">
    <style>
        #loadMoreMoviesButton {
            width: 200px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f0f0f0;
            border: 1px solid #ccc;
            margin: 10px;
            text-align: center;
            font-size: 18px;
            cursor: pointer;
        }
        .movies-container {
            display: flex;
            flex-wrap: wrap;
        }
        .box {
            position: relative;
            margin: 10px;
        }
        .delete-icon {
            position: absolute;
            top: 5px;
            right: 5px;
            width: 20px;
            height: 20px;
            background: red;
            color: white;
            text-align: center;
            line-height: 20px;
            cursor: pointer;
            display: none; /* Initially hidden */
        }
        #addMovieButton {
            width: 200px;
            height: 50px;
            display: none; /* Initially hidden */
            align-items: center;
            justify-content: center;
            background: #f0f0f0;
            border: 1px solid #ccc;
            margin: 10px auto;
            text-align: center;
            font-size: 18px;
            cursor: pointer;
        }
        .modify-button {
            display: none; /* Initially hidden */
            margin-top: 10px;
            padding: 5px;
            background: #4CAF50;
            color: white;
            text-align: center;
            cursor: pointer;
        }
        .movie-buttons {
            display: flex;
            justify-content: center;
            gap: 10px;
        }
        .movie-buttons-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav>
        <ul>
            <li>
                <div class="text-container">
                    <div class="big-text">HuiKing-Movie</div>
                </div>
            </li>
            <li class="search-bar">
                <input type="text" id="searchInput" placeholder="搜索...">
                <button onclick="search()"><i class="iconfont iconchazhao"></i></button>
            </li>
            <li><a href="https://www.taobao.com" target="_blank">编者推荐</a></li>
            <li><a href="https://yiyan.baidu.com/" target="_blank">AI导航</a></li>
            <li><a href="javascript:goToMyPage()">我的</a></li>
        </ul>
    </nav>
    <!-- 轮播图 -->
    <div class="focu">
        <div class="focus">
            <ul>
                <li><a href="#"><img src="images/focus1.jpg" alt=""></a></li>
                <li><a href="#"><img src="images/focus2.jpg" alt=""></a></li>
                <li><a href="#"><img src="images/focus3.jpg" alt=""></a></li>
                <li><a href="#"><img src="images/focus4.jpg" alt=""></a></li>
            </ul>
            <a href="javascript:;" class="bt-l">&lt;</a>
            <a href="javascript:;" class="bt-r">&gt;</a>
            <ol class="circle"></ol>
        </div>
    </div>
    <!-- 电影板块 -->
    <div class="movies-container">
        <div class="movie-header">
            <h1>电影</h1>
            <div class="movie-buttons-container">
                <div class="movie-buttons">
                    <button onclick="displayMovies('latest_films')">最新电影</button>
                    <button onclick="displayMovies('highest_rated_films')">最多推荐</button>
                    <button onclick="displayMovies('most_loved_films')">最多收藏</button>
                </div>
                <button id="addMovieButton" onclick="showAddMovieModal()">新增电影</button>
            </div>
        </div>
        <hr>
        <div id="moviesSection"></div>
        <div id="loadMoreContainer" style="text-align:center; margin-top:20px;">
            <button id="loadMoreMoviesButton" onclick="loadMoreMovies()">获取更多电影</button>
        </div>
    </div>

    <script>
        window.onload = async function() {
            const identity = localStorage.getItem('identity');
            if (identity === '0') {
                await fetchUserInfo();
            } else {
                fetchMovies();
                if (identity === '1') {
                    document.getElementById('addMovieButton').style.display = 'flex';
                }
            }
        };

        async function fetchUserInfo() {
            const token = localStorage.getItem('access_token');
            const userId = localStorage.getItem('user_id');
            const apiUrl = 'http://192.168.78.248:5000/user_infor';

            const requestData = {
                user_id: userId,
                code: 1 // 用户标记
            };

            try {
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(requestData)
                });

                if (response.status === 200) {
                    const result = await response.json();
                    if (result.infor.block_not === true) {
                        showBlockPopup();
                    } else {
                        fetchMovies();
                    }
                } else {
                    console.error("Failed to fetch user info");
                }
            } catch (error) {
                console.error("Error fetching user info:", error);
            }
        }

        function showBlockPopup() {
            const blockPopup = document.createElement('div');
            blockPopup.style.position = 'fixed';
            blockPopup.style.top = '0';
            blockPopup.style.left = '0';
            blockPopup.style.width = '100%';
            blockPopup.style.height = '100%';
            blockPopup.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
            blockPopup.style.display = 'flex';
            blockPopup.style.alignItems = 'center';
            blockPopup.style.justifyContent = 'center';
            blockPopup.innerHTML = `
                <div style="background: white; padding: 20px; text-align: center;">
                    <p>您已被封禁，点击去申诉</p>
                    <button onclick="goToAppealPage()">去申诉</button>
                </div>
            `;
            document.body.appendChild(blockPopup);
        }

        function goToAppealPage() {
            window.location.href = 'user_dashboard.html';
        }

        async function fetchMovies() {
            const token = localStorage.getItem('access_token');
            const userId = localStorage.getItem('user_id');
            let apiUrl = 'http://192.168.78.248:5000/main_ui';

            const requestData = {
                user_id: parseInt(userId)
            };

            try {
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(requestData)
                });

                if (response.status === 200) {
                    const result = await response.json();
                    moviesData = result;
                    localStorage.setItem('moviesData', JSON.stringify(moviesData));
                    displayMovies(currentCategory);
                } else {
                    console.error("Failed to fetch movies");
                }
            } catch (error) {
                console.error("Error fetching movies:", error);
            }
        }

        let currentRole = localStorage.getItem('identity') || 'guest';
        const userRoleDiv = document.getElementById('userRole');
        let moviesData = {};
        let lastFilmId = 0;
        let currentCategory = 'latest_films';

        function goToMyPage() {
            const identity = localStorage.getItem('identity');
            if (identity === '0') {
                window.location.href = 'user_dashboard.html';
            } else if (identity === '1') {
                window.location.href = 'superadmin_dashboard.html';
            } else if (identity === '2') {
                window.location.href = 'admin_dashboard.html';
            }
        }

        function displayMovies(category) {
            currentCategory = category;
            const moviesSection = document.getElementById('moviesSection');
            moviesSection.innerHTML = '';
            const movies = moviesData[category] || [];
            movies.forEach(movie => {
                const movieDiv = document.createElement('div');
                movieDiv.className = 'box';
                movieDiv.innerHTML = `
                    <a href="movie.html?film_id=${movie.film_id}" onclick="saveFilmId(${movie.film_id})"><img src="${movie.www_http}" alt="${movie.film_name}"></a>
                    <h4><a href="movie.html?film_id=${movie.film_id}" onclick="saveFilmId(${movie.film_id})">${movie.film_name}</a></h4>
                    <button class="modify-button" onclick="showModifyMovieModal(${movie.film_id})">修改电影</button>
                    <div class="delete-icon" onclick="confirmDeleteMovie(${movie.film_id})">×</div>
                `;
                moviesSection.appendChild(movieDiv);
                lastFilmId = movie.film_id;
            });

            if (currentRole === '1') {
                document.querySelectorAll('.delete-icon').forEach(icon => {
                    icon.style.display = 'block';
                });
                document.querySelectorAll('.modify-button').forEach(button => {
                    button.style.display = 'block';
                });
            }

            const loadMoreContainer = document.getElementById('loadMoreContainer');
            if (!loadMoreContainer.contains(document.getElementById('loadMoreMoviesButton'))) {
                loadMoreContainer.appendChild(document.getElementById('loadMoreMoviesButton'));
            }
        }

        function saveFilmId(filmId) {
            localStorage.setItem('selectedFilmId', filmId);
        }

        function search() {
            const searchInput = document.getElementById('searchInput').value;
            const userId = localStorage.getItem('user_id') || 'guest';
            const token = localStorage.getItem('access_token');

            if (searchInput.trim() === '') {
                alert('请输入搜索内容');
                return;
            }

            const requestData = {
                user_id: parseInt(userId),
                search: searchInput
            };

            fetch('http://192.168.78.248:5000/search', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'successfully') {
                    localStorage.setItem('searchResults', JSON.stringify(data.film));
                    window.location.href = 'search.html';
                } else {
                    alert('暂无搜索结果');
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }

        function showAddMovieModal() {
            const filmName = prompt("请输入电影名称:");
            const actor = prompt("请输入演员:");
            const director = prompt("请输入导演:");
            const releaseTime = prompt("请输入上映时间:");
            const introductory = prompt("请输入简介:");
            const wwwHttp = prompt("请输入图片地址:");

            if (filmName && actor && director && releaseTime && introductory && wwwHttp) {
                addMovie(filmName, actor, director, releaseTime, introductory, wwwHttp);
            }
        }

        function showModifyMovieModal(filmId) {
            const filmName = prompt("请输入新的电影名称（留空则不修改）:");
            const actor = prompt("请输入新的演员（留空则不修改）:");
            const director = prompt("请输入新的导演（留空则不修改）:");
            const releaseTime = prompt("请输入新的上映时间（留空则不修改）:");
            const introductory = prompt("请输入新的简介（留空则不修改）:");

            let content = {};
            if (filmName) content.film_name = filmName;
            if (actor) content.actor = actor;
            if (director) content.director = director;
            if (releaseTime) content.release_time = releaseTime;
            if (introductory) content.introductory = introductory;

            if (Object.keys(content).length > 0) {
                modifyMovie(filmId, content);
            }
        }

        function confirmDeleteMovie(filmId) {
            if (confirm("是否确认删除？")) {
                deleteMovie(filmId);
            }
        }

        async function deleteMovie(filmId) {
            const token = localStorage.getItem('access_token');
            const userId = localStorage.getItem('user_id');

            const requestData = {
                user_id: parseInt(userId),
                code: 1, // 删除电影
                film_id: filmId
            };

            try {
                const response = await fetch('http://192.168.78.248:5000/super_film', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(requestData)
                });

                if (response.status === 200) {
                    alert('电影删除成功');
                    fetchMovies(); // 重新获取电影列表
                } else {
                    console.error("Failed to delete movie");
                }
            } catch (error) {
                console.error("Error deleting movie:", error);
            }
        }

        async function addMovie(filmName, actor, director, releaseTime, introductory, wwwHttp) {
            const token = localStorage.getItem('access_token');
            const userId = localStorage.getItem('user_id');

            const requestData = {
                user_id: parseInt(userId),
                code: 0, // 新增电影
                film_name: filmName,
                actor: actor,
                director: director,
                release_time: releaseTime,
                introductory: introductory,
                www_http: wwwHttp
            };

            try {
                const response = await fetch('http://192.168.78.248:5000/super_film', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(requestData)
                });

                if (response.status === 200) {
                    alert('电影新增成功');
                    fetchMovies(); // 重新获取电影列表
                } else {
                    console.error("Failed to add movie");
                }
            } catch (error) {
                console.error("Error adding movie:", error);
            }
        }

        async function modifyMovie(filmId, content) {
            const token = localStorage.getItem('access_token');
            const userId = localStorage.getItem('user_id');

            const requestData = {
                user_id: parseInt(userId),
                code: 2, // 修改电影
                film_id: filmId,
                content: content
            };

            try {
                const response = await fetch('http://192.168.78.248:5000/super_film', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(requestData)
                });

                if (response.status === 200) {
                    alert('电影修改成功');
                    fetchMovies(); // 重新获取电影列表
                } else {
                    console.error("Failed to modify movie");
                }
            } catch (error) {
                console.error("Error modifying movie:", error);
            }
        }

        async function loadMoreMovies() {
            const token = localStorage.getItem('access_token');
            const userId = localStorage.getItem('user_id');
            const filmTypeMap = {
                'latest_films': 'release_time',
                'highest_rated_films': 'film_mark',
                'most_loved_films': 'love_num'
            };
            const filmType = filmTypeMap[currentCategory];

            const requestData = {
                user_id: parseInt(userId),
                more: 1,
                film_type: filmType,
                last_id: lastFilmId
            };

            try {
                const response = await fetch('http://192.168.78.248:5000/main_ui', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(requestData)
                });

                if (response.status === 200) {
                    const result = await response.json();
                    appendMovies(result.more, currentCategory);
                } else {
                    console.error("Failed to load more movies");
                }
            } catch (error) {
                console.error("Error loading more movies:", error);
            }
        }

        function appendMovies(newMovies, category) {
            const moviesSection = document.getElementById('moviesSection');
            newMovies.forEach(movie => {
                const movieDiv = document.createElement('div');
                movieDiv.className = 'box';
                movieDiv.innerHTML = `
                    <a href="movie.html?film_id=${movie.film_id}" onclick="saveFilmId(${movie.film_id})"><img src="${movie.www_http}" alt="${movie.film_name}"></a>
                    <h4><a href="movie.html?film_id=${movie.film_id}" onclick="saveFilmId(${movie.film_id})">${movie.film_name}</a></h4>
                    <button class="modify-button" onclick="showModifyMovieModal(${movie.film_id})">修改电影</button>
                    <div class="delete-icon" onclick="confirmDeleteMovie(${movie.film_id})">×</div>
                `;
                moviesSection.appendChild(movieDiv);
                if (!moviesData[category]) {
                    moviesData[category] = [];
                }
                moviesData[category].push(movie);
                lastFilmId = movie.film_id;
            });
            localStorage.setItem('moviesData', JSON.stringify(moviesData));

            if (currentRole === '1') {
                document.querySelectorAll('.delete-icon').forEach(icon => {
                    icon.style.display = 'block';
                });
                document.querySelectorAll('.modify-button').forEach(button => {
                    button.style.display = 'block';
                });
            }
        }
    </script>
</body>
</html>
